<?php
namespace app\erp\model;

use think\Model;

class GoodsAccessorydb extends Model
{

    protected $pk = 'goods_accessory_id';

    protected $name = 'goods_accessory';

    protected $type = [
        'create_time' => 'timestamp:Y-m-d'
    ];
    // 自动完成时间转换
    protected $autoWriteTimestamp = true;
    // 自动完成
    protected $insert = [
        'site_id'
    ];

    protected function setSiteIdAttr($value)
    {
        if (! $value) {
            return SITE_ID;
        }
        if ($value == 0) {
            return null;
        }
        return $value;
    }

    public $param = array();

    public function scopeGoodsSku($query, $goods_sku)
    {
        $query->where('goods_sku', $goods_sku);
    }
    // 基础查询
    public function base($query)
    {
        if (isset($this->param['site_id'])) {
            if ($this->param['site_id'] == 0 || $this->param['site_id'] == '') {
                $query->where('site_id', 'null');
            } else {
                $query->where('site_id', $this->param['site_id']);
            }
        } else {
            if (! empty(SITE_ID)) {
                $query->where('site_id', SITE_ID);
            } else {
                $query->where('site_id', 'null');
            }
        }
        if (isset($this->param['goods_sku'])) {
            $query->goodsSku($this->param['goods_sku']);
        }
    }
    // 保存
    public function ajaxSave()
    {
        $this->where('goods_sku', $this->param['goods_sku'])
            ->where('site_id', $this->param['site_id'])
            ->delete();
        foreach ($this->param['data'] as $key=>$val){
            $this->param['data'][$key]['accessory_param'] = json_encode($val['accessory_param']);
            $this->param['data'][$key]['accessory_api'] = json_encode($val['accessory_api']);
        }
        $this->allowField(true)->saveAll($this->param['data'], false);
        
        return 'success';
    }
    public function ajaxUpdateAll(){
        $this->saveAll($this->param['data']);
        return 'success';
    }
    // 列表
    public function ajaxList()
    {
        $data = $this->order('goods_accessory_id asc')->select();
        if ($data) {
            $data = $data->toArray();
        } else {
            $data = array();
        }
        return $data;
    }
    // 软删除
    public function ajaxDelete()
    {
        if (isset($this->param['goods_sku'])) {
            $this->delete();
        }
        return 'success';
    }
}